package com.example.ingredients_regulation_batchprint.controller;


import cn.afterturn.easypoi.word.WordExportUtil;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.Forest;
import com.dtflys.forest.annotation.PostRequest;
import com.dtflys.forest.http.ForestResponse;
import com.example.ingredients_regulation_batchprint.forsetClient.QsyaClient;
import com.example.ingredients_regulation_batchprint.utils.LoadConfigUtil;
import com.example.ingredients_regulation_batchprint.utils.WordUtils;
//import com.spire.doc.Document;
//import com.spire.doc.FileFormat;
//import com.spire.doc.Section;
//import com.spire.doc.TextWatermark;
//import com.spire.doc.documents.WatermarkLayout;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.annotation.Resource;
import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;



public class POSTUrl {

    static String forestUrl = "127.0.0.1:5555";

    //    public static void main(String[] args) throws IOException {
//
////        FileSystemView systemView = FileSystemView.getFileSystemView();
////        File homeDirectory = systemView.getHomeDirectory();
////        //桌面路径
////        String path = homeDirectory.getPath();
////        System.out.println(path);
//        String userHome = System.getProperties().getProperty("user.home");
//
//        System.out.println("☑");
//    }


    public JSONObject batchPrint(String ids, String printType, String title, String paperType) throws Exception {

        JSONObject js = new JSONObject();
        js.put("code", 200);

        StopWatch watch = new StopWatch();

// 实例化Forest请求接口
        QsyaClient qsyaClient = Forest.client(QsyaClient.class);

        watch.start("Forest");

        ForestResponse<JSONObject> data = null;

        //防止操作失误，默认打开测试区域管理
        Properties config = LoadConfigUtil.loadConfig();

        if (StringUtils.isNotBlank(config.getProperty("forestUrl"))) {
            forestUrl = config.getProperty("forestUrl");
        }
        try {
            if ("distribution".equals(printType)) {
                data = qsyaClient.queryGysDistributionManagementData(forestUrl, ids, printType, title, paperType);
            } else if ("stock".equals(printType)) {
                data = qsyaClient.queryXxStockManagementData(forestUrl, ids, printType, title, paperType);
            } else {
                js.put("code", 500);
                js.put("message", "打印错误");
                return js;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        watch.stop();
// 用isError方法判断请求是否失败, 比如404, 500等情况
        if (data.isError()) {
//            int status = data.getStatusCode(); // 获取请求响应状态码
//            String content = data.getContent(); // 获取请求的响应内容
//            JSONObject result = data.getResult(); // 获取方法返回类型对应的最终数据结果
            //统一返回
            js.put("code", 500);
            js.put("message", "网络异常");
            return js;
        }

        JSONObject aa = JSONObject.parseObject(data.getContent());

        if (!"200".equals(aa.get("code").toString())) {
            js.put("code", 500);
            js.put("message", aa.get("message").toString());
            return js;
        }

        //获取桌面路径
//        FileSystemView systemView = FileSystemView.getFileSystemView();
//        File homeDirectory = systemView.getHomeDirectory();
//        String downLoadPath = homeDirectory.getPath()+"\\downLoadPath\\";
        //获取用户路径
        String userHome = System.getProperties().getProperty("user.home");
        String downLoadPath = userHome + "\\data_qsya\\downLoad\\";
        //定义wrod的list
        List<XWPFDocument> wordList = new ArrayList<>();

        XWPFDocument work;

        List<Map<String, Object>> list = (List<Map<String, Object>>) aa.get("list");

        //下载文件到本地
        System.out.println(aa.get("url").toString() + ".docx");


        watch.start("downLoadTemplate");
        boolean b = downLoadFromUrl(aa.get("url").toString(), aa.get("printName").toString() + ".docx", downLoadPath);
        watch.stop();

        watch.start("GenerateFile");
//            boolean b = downLoadNxtFile(id + ".docx", downLoadPath);
        if (b) {

//            tjshuiyin(downLoadPath + aa.get("printName").toString() + ".docx", aa);

            try {
                for (Map<String, Object> map : list) {
                    //使用模板赋值
                    work = WordExportUtil.exportWord07(downLoadPath + aa.get("printName").toString() + ".docx", map);
                    wordList.add(work);
                }
                File file = new File(downLoadPath + aa.get("printName").toString() + ".docx");
                file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 定义一个文件名称
        long fileName = System.currentTimeMillis();

        //判断文件是否生成
        if (CollectionUtils.isEmpty(wordList)) {
            js.put("code", 500);
            js.put("message", "生成文件失败，请重新生成");
            return js;
        }

        XWPFDocument doc = WordUtils.mergeWord(wordList);
        FileOutputStream fos = new FileOutputStream(downLoadPath + fileName + ".docx");
        doc.write(fos);
        fos.close();
        watch.stop();
//使用流的方式合成文件写入
//        for (XWPFDocument word : wordList) {
//
//            ByteArrayOutputStream out = new ByteArrayOutputStream();
//            word.write(out);
//            byte[] bookByteAry = out.toByteArray();
//            InputStream in = new ByteArrayInputStream(bookByteAry);
//
//            document.insertTextFromStream(in, FileFormat.Docx_2013);
//            out.close();
//            in.close();
//        }
//        document.saveToFile(downLoadPath + fileName + ".docx", FileFormat.Docx_2013);

        File file = new File(downLoadPath + fileName + ".docx");

        if (!file.exists()) {
            js.put("code", 500);
            js.put("message", "生成文件失败，请重新生成");
            return js;
        }
        js.put("message", "文件生成成功");
        System.out.println("文件生成成功");

        js.put("url", downLoadPath + fileName + ".docx");
        System.out.println("打印结果描述" + watch.prettyPrint());
        System.out.println("任务的数量==>" + watch.getTaskCount());
        System.out.println("最后执行的任务==>" + watch.getLastTaskInfo().getTaskName());
        return js;
    }


    /**
     * 添加水印
     *
     * @param fileName
     * @param aa
     * @return
     * @throws IOException
     */

//    public static void tjshuiyin(String fileName, Map aa) throws IOException {
//        //添加水印
//        //Create a Document instance 创建一个文档实例
//        Document document = new Document();
//        //Load a sample Word document 加载一个Word文档样本
//        document.loadFromFile(fileName);
//        //Get the first section 获取第一部分
//        Section section = document.getSections().get(0);
//        //Create a TextWatermark instance 创建一个TextWatermark实例
//        TextWatermark txtWatermark = new TextWatermark();
//        //Set the format of the text watermark 设置文本水印的格式
//        txtWatermark.setText(aa.get("watermark").toString());
////            txtWatermark.setText("这个是水印");
//        txtWatermark.setFontSize(30);
//        txtWatermark.setColor(Color.black);
//        //Diagonal对角线 Horizontal横向
//        txtWatermark.setLayout(WatermarkLayout.Diagonal);
//        //Add the text watermark to document 将文字水印添加到文档中
//        section.getDocument().setWatermark(txtWatermark);
//        //Save the document to file 将文件保存到文件中
//        document.saveToFile(fileName, FileFormat.Docx);
//
//    }

    public static boolean downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {

        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间
        conn.setConnectTimeout(10 * 1000);
        //设置一个请求头
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //获得输入流
        InputStream inputStream = conn.getInputStream();
        //获取数组
        byte[] getData = readInputStream(inputStream);
        //文件保存路径
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (null != fos) {
            fos.close();
        }
        if (null != inputStream) {
            inputStream.close();
        }

        if (!file.exists()) {
            System.out.println("下载文件失败");
            return false;
        }
        System.out.println("info:" + url + " download success");
        return true;
    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


}
